package com.tomato.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tomato.order.OrderFrom.OrderFrom;
import com.tomato.order.VO.ResultVO;
import com.tomato.order.entity.OrderDetail;
import com.tomato.order.entity.OrderMaster;
import com.tomato.order.entity.Product;
import com.tomato.order.mapper.OrderDetailMapper;
import com.tomato.order.mapper.OrderMasterMapper;
import com.tomato.order.mapper.ProductMapper;
import com.tomato.order.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping("/api/order")
@Slf4j
public class OrderController {
    @Resource
    private ProductMapper productMapper;
    @Resource
    private OrderMasterMapper orderMasterMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;

    @PostMapping("/create")
    @Transactional
    public ResultVO createOrder(@RequestBody OrderFrom orderFrom) {
        Gson gson = new Gson();
        List<OrderDetail> orderDetailList = new ArrayList<>();
        try {
            orderDetailList = gson.fromJson(orderFrom.getItems(), new TypeToken<List<OrderDetail>>() {
            }.getType());
        } catch (Exception e) {
            log.error("【对象转换】错误，string={}", orderFrom.getItems());
        }
        orderFrom.setOrderDetailList(orderDetailList);
        if (CollectionUtils.isEmpty(orderDetailList)) {
            log.error("【创建订单】购物车不能为空");
            return R.error(1, "购物车不能为空");
        }
        //创建订单
//        String orderId = UUID.randomUUID().toString();
        Random random = new Random(47);
        String rand = String.valueOf(Math.abs(random.nextInt(10000)));
        String orderId = System.currentTimeMillis() + rand;
        double orderAmount = 0;
        for (int i = 0; i < orderDetailList.size(); i++) {
            Product product = productMapper.selectOne(new QueryWrapper<Product>().
                    eq("id", orderDetailList.get(i).getId().toString()));
            orderAmount += product.getPrice() * orderDetailList.get(i).getCount();
            orderDetailList.get(i).setOrderId(orderId);
            orderDetailList.get(i).setDetailId(UUID.randomUUID().toString());
            orderDetailList.get(i).setProductName(product.getName());
            orderDetailList.get(i).setProductPrice(product.getPrice());
            orderDetailList.get(i).setProductIcon(product.getImage());
            int stock = product.getStock() - orderDetailList.get(i).getCount();
            if (stock < 0) {
                return R.error(1, "支付失败,库存不足");
            }
            product.setStock(stock);
            product.setSellCount(product.getSellCount() + orderDetailList.get(i).getCount());
            productMapper.updateById(product);
            OrderDetail orderDetail = orderDetailList.get(i);
            orderDetailMapper.insert(orderDetail);
        }
        OrderMaster orderMaster = new OrderMaster();
        orderMaster.setOrderId(orderId);
        orderMaster.setBuyerOpenid(orderFrom.getOpenid());
        orderMaster.setBuyerName(orderFrom.getName());
        orderMaster.setBuyerAddress(orderFrom.getAddress());
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setPayStatus(0);
        orderMaster.setOrderStatus(0);
        orderMaster.setOrderDetailList(orderDetailList);
        orderMasterMapper.insert(orderMaster);
        return R.success(orderMaster);
    }

    @GetMapping("/list")
    public ResultVO list(@RequestParam("buyer_openid") String buyer_openid) {
        List<OrderMaster> list = orderMasterMapper.selectList(new QueryWrapper<OrderMaster>().
                eq("buyer_openid", buyer_openid).
                orderByDesc("create_time"));
        return R.success(list);
    }

    @GetMapping("/delete")
    public ResultVO delete(@RequestParam("orderId") String orderId) {
        orderDetailMapper.delete(new QueryWrapper<OrderDetail>().eq("order_id", orderId));
        int result = orderMasterMapper.delete(new QueryWrapper<OrderMaster>().eq("order_id", orderId));
        if (result == 1) {
            return R.success("订单删除成功！");
        } else {
            return R.error(1, "订单删除失败！");
        }
    }
}
